package com.zh.chat.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;

import com.zh.chat.entity.Friend;
import com.zh.chat.entity.UDPProtocol;
import com.zh.chat.entity.UserInfo;


/**
 * 用来写XML和聊天记录文件的工具
 * @author Administrator
 *
 */
public class FileOperationUtil {
	private static Logger log = Logger.getLogger(FileOperationUtil.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	
	/**
	 * 根据文件类型和用户ID生成不同的路径
	 * @param fileType
	 * @param id
	 * @return
	 */
	public static String getFilePath(int fileType, java.lang.Long id, String fileName){
		String path = null;
		switch (fileType) {
		case FileType.IMAGE:
			path = "images"+File.separatorChar;
			break;
		case FileType.DATA:
			path = "data"+File.separatorChar + id +File.separatorChar;
			break;
		case FileType.ATTACHMENT:
			path = "attachment"+File.separatorChar;
			break;
		case FileType.SCULPTURE:
			path = "data"+ File.separatorChar + id +File.separatorChar+"sculpture"+File.separatorChar;
			break;
		case FileType.CHATLOG:
			path = "data"+ File.separatorChar + id +File.separatorChar+"chatlog"+File.separatorChar;
			break;
		default:
			path = "other"+File.separatorChar;
			break;
		}
		if(fileName!=null){
			path += fileName;
		}
		return path;
	}
	
	public static void appendChatLog(Friend friend, UserInfo userInfo, UDPProtocol request) throws IOException{
		String path = FileOperationUtil.getFilePath(FileType.CHATLOG, friend.getSysId(), friend.getFriendId()+".log");
		File file = new File(path);
		File pFile = file.getParentFile();
		if(!pFile.exists()){
			pFile.mkdirs();
		}
		if(!file.exists()){
			if(!file.createNewFile()){
				log.error("聊天日志生成失败");
				return;
			}
		}
		FileWriter fw = new FileWriter(file.getAbsolutePath(),true);
		PrintWriter pw = new PrintWriter(fw);
		if(request.getRequestId()==0){
			pw.println(userInfo.getNickname()+" ("+userInfo.getSysId()+") "+sdf.format(new java.util.Date()));
		}else{
			pw.println(friend.getNickname()+" ("+friend.getFriendId()+") "+sdf.format(new java.util.Date()));
		}
		pw.println(request.getData().toString());
		pw.println("");
		pw.flush();
		pw.close();
		fw.close();
		log.info("聊天日志已追加");
	}
	

	public static String getChatLog(String path) throws FileNotFoundException{
		String content = "";
		InputStreamReader dis = null;
		File file = new File(path);
		try {
			InputStream fis = new FileInputStream(file);
			dis = new InputStreamReader(fis);
			if(dis!=null){
				BufferedReader br = new BufferedReader(dis);
				String line = null;
				while ((line = br.readLine()) != null) {
					content+=line+"\t\n";
				}
				//关闭输入流
				dis.close();
				dis=null;
				br.close();
				br=null;
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(dis!=null){
					dis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		long now = System.currentTimeMillis();
		long modify = file.lastModified();
		int MINUTE = 1;//设置出现分隔符时间一分钟
		long range = MINUTE*60;
		long r = (now-modify)/1000;
		int hour = (int) (r/3600);
		int minute = (int)(r-hour*3600)/60;
		if(r > range){
			if(hour==0){
				content+="------"+minute+"分 以前的历史日志-----\t\n";
			}else{
				content+="------"+hour+"小时"+minute+"分 以前的历史日志-----\t\n";
			}
		}
		return content;
	}
	
	public static JSONArray getFileJSONArray(String path) throws FileNotFoundException{
		JSONArray jarr = null;
		InputStreamReader dis = null;
		try {
			InputStream fis = new FileInputStream(path);
			dis = new InputStreamReader(fis);
			if(dis!=null){
				BufferedReader br = new BufferedReader(dis);
				String json = "";
				String line = null;
				while ((line = br.readLine()) != null) {
					json+=line;
				}
				//关闭输入流
				dis.close();
				dis=null;
				br.close();
				br=null;
				jarr = JSONArray.fromObject(json);
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(dis!=null){
					dis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jarr;
	}
}
